﻿using System;
using System.Collections.Generic;
using System.Web;
using DCCMS.Model;
using System.Web.Security;
using System.Collections;

namespace DCCMS.Web.Admin
{
    public class AdminBasePage:System.Web.UI.Page
    {
        private AdminUser _currentuser;
        public AdminUser CurrentUser
        {
            get
            {
                return _currentuser;
            }
            set
            {
                _currentuser.UserName = "Admin";
                _currentuser.UserPWD = "admin888";
                _currentuser = value;
            }
        }
        /// <summary>
        /// 获取本页是否在受保护目录,受保护的目录是admin目录
        /// </summary>
        protected bool IsAdminDir
        {
            get
            {
                return Request.FilePath.IndexOf("/admin") == 0;
            }
        }

        /// <summary>
        /// 防止session超时,如果超时就注销身份验证并提示和转向到网站默认页
        /// </summary>
        private void PreventSessionTimeout()
       {
           if(!this.IsAdminDir) return;
           if(Session["User_Name"]==null&&this.IsAdminDir)
           {            
              System.Web.Security.FormsAuthentication.SignOut();
              this.Alert("登陆超时", Request.ApplicationPath);
           }
       }
        /// <summary>
        /// 每次刷新本页面的时候更新Cache里的登陆时间选项,在下面的OnInit方法里调用.
        /// </summary>
        private void UpdateCacheTime()
        {
            Hashtable h = (Hashtable)Cache["DCCMS"];
            if (h != null)
            {
                ((ArrayList)h[Session.SessionID])[1] = DateTime.Now;
            }
            Cache["DCCMS"] = h;
        }
        /// <summary>
        /// 在跟踪里输出一个HashTable的所有元素,在下面的OnInit方法里调用.以便方便的观察缓存数据
        /// </summary>
        /// <param name="myList"></param>
        private void TraceValues(Hashtable myList)
        {
            IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
            int i = 0;
            while (myEnumerator.MoveNext())
            {
                Context.Trace.Write("onlineSessionID" + i, myEnumerator.Key.ToString());
                ArrayList al = (ArrayList)myEnumerator.Value;
                Context.Trace.Write("onlineName" + i, al[0].ToString());
                Context.Trace.Write("onlineTime" + i, al[1].ToString());
                TimeSpan ts = System.DateTime.Now.Subtract(Convert.ToDateTime(al[1].ToString()));
                Context.Trace.Write("当前的时间和此登陆时间间隔的秒数", ts.TotalSeconds.ToString());
                i++;
            }
        }
        /// <summary>
        /// 弹出信息并返回到指定页
        /// </summary>
        /// <param name="msg">弹出的消息</param>
        /// <param name="url">指定转向的页面</param>
        protected void Alert(string msg, string url)
        {
            string scriptString = "<script language=JavaScript>alert(\"" + msg + "\");location.href=\"" + url + "\"</script>";
            if (!this.IsStartupScriptRegistered("alert"))
                this.RegisterStartupScript("alert", scriptString);
        }
        /// <summary>
        /// 为了防止常时间不刷新页面造成会话超时,这里写一段脚本,每隔一分钟向本页发送一个请求以维持会话不被超时，这里用的是xmlhttp的无刷新请求
        /// 这个方法也在下面的OnInit方法里调用
        /// </summary>
        protected void XmlReLoad()
        {
            //System.Text.StringBuilder htmlstr = new System.Text.StringBuilder();
            //htmlstr.Append("<SCRIPT LANGUAGE=\"JavaScript\">");
            //htmlstr.Append("function GetMessage(){");
            //htmlstr.Append("  var xh=new ActiveXObject(\"Microsoft.XMLHTTP\");");
            //htmlstr.Append("  xh.open(\"get\",window.location,false);");
            //htmlstr.Append("  xh.send();");
            //htmlstr.Append("  window.setTimeout(\"GetMessage()\",60000);");
            //htmlstr.Append("}");
            //htmlstr.Append("window.onload=GetMessage();");
            //htmlstr.Append("</SCRIPT>       ");
            //if (!this.IsStartupScriptRegistered("xmlreload"))
            //    this.RegisterStartupScript("alert", htmlstr.ToString());
        }

        protected override void OnInit(EventArgs e)
        {         
            base.OnInit(e);
            //this.PreventSessionTimeout();
            //this.UpdateCacheTime();
            //this.XmlReLoad();
            //if (this.Cache["DCCMS"] != null)
            //{
            //    this.TraceValues((System.Collections.Hashtable)Cache["DCCMS"]);
            //}
        }

        protected string GetRedirectUrl(string defaultUrl)
        {
            HttpContext context = HttpContext.Current;
            string returnUrl = context.Request.QueryString["ReturnUrl"];
            if (returnUrl == null)
            {
                return defaultUrl;
            }
            return HttpUtility.UrlDecode(returnUrl);
        }
        protected void LoginOut()
        {
            FormsAuthentication.SignOut();
            HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            FormsAuthentication.RedirectToLoginPage();
        }
    }
}